package com.three.event;

import com.google.common.eventbus.Subscribe;
import com.three.api.event.PlayerOfflineEvent;
import com.three.api.event.PlayerOnlineEvent;
import com.three.api.spi.common.MQClient;
import com.three.api.spi.common.MQClientFactory;
import com.three.common.message.player.NotifyPlayerInfoMessage;
import com.three.common.player.PlayerManager;
import com.three.domain.player.PlayerPo;
import com.three.repository.PlayerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.three.api.event.Topics.OFFLINE_CHANNEL;
import static com.three.api.event.Topics.ONLINE_CHANNEL;

/**
 * Created by mathua on 2017/5/25.
 */
@Component
/*package*/ final class PlayerEventConsumer extends EventConsumer {

    private final MQClient mqClient = MQClientFactory.create();

    @Autowired
    private PlayerRepository playerRepository;

    @Subscribe
    void on(PlayerOnlineEvent event) {
        PlayerManager.I.addToOnlineList(event.getPlayerId());
        mqClient.publish(ONLINE_CHANNEL, event.getPlayerId());

        PlayerPo player = playerRepository.getOne(event.getPlayerId());

        NotifyPlayerInfoMessage.from(event.getConnection())//
                .setPlayerId(player.getPlayerId())//
                .setNickName(player.getNickName())//
                .setHead(player.getHead())//
                .setLevel(player.getLevel())//
                .setExp(player.getExp())//
                .setProvinceID(player.getProvinceID())//
                .setCity(player.getCity())//
                .setPhone(player.getPhone())//
                .setGender(player.getGender())//
                .setGold(player.getGold())//
                .setDiamond(player.getDiamond())//
                .send();
    }

    @Subscribe
    void on(PlayerOfflineEvent event) {
        PlayerManager.I.remFormOnlineList(event.getPlayerId());
        mqClient.publish(OFFLINE_CHANNEL, event.getPlayerId());
    }
}
